const sequenceUtil = require('../util/sequenceUtil');
const wxPayUtil = require('../util/wxPayUtil');
const paymentStatus = require('../constants/paymentStatus');
// const businessType = require('../constants/businessType');
module.exports = class extends think.Model {
  removePayment(id) {
    return this.where({
      id
    }).delete();
  }
  queryById(id, field = '*') {
    return this.where({id}).field(field).select();
  }
  removeById(id) {
    return this.where({id}).delete();
  }
  verifyPaymentSign(result) {
    const sign = result.sign;
    delete result.sign;
    if (wxPayUtil.sign(result) === sign) {
      return true;
    }
    return false;
  }
  queryByOutTradeNo(outTradeNo, fields = '*') {
    return this.where({
      out_trade_no: outTradeNo
    }).field(fields).find();
  }
  paySuccess(id, {transactionId}) {
    return this.where({id, status: paymentStatus.notpayed}).update({
      transaction_id: transactionId,
      status: paymentStatus.payed,
      modify_time: think.datetime(),
      pay_time: think.datetime()
    });
  }
  async create({
    businessId,
    userId,
    amount,
    ip,
    openid,
    notifyUrl
  }) {
    try {
      const data = {
        business_id: businessId,
        amount,
        create_time: think.datetime()
      };
      const no = sequenceUtil.generateOutradeNo(userId);
      data.out_trade_no = no;
      // 统一下单
      const rt = await wxPayUtil.miniproOrder({
        openid,
        outTradeNo: no,
        fee: amount,
        ip,
        notifyUrl
      });
      const paymentId = await this.add(data);
      rt.paymentId = paymentId;
      return rt;
    } catch (e) {
      think.logger.error('创建订单失败,payment:create:', e);
      throw e;
    }
  }
};
